package com.sf.bigscreen.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.bigscreen.mapper.IDayAmMapper;
import com.sf.bigscreen.mapper.ITableConfigMapper;
import com.sf.bigscreen.model.DayAm;
import com.sf.bigscreen.model.TableConfig;
import com.sf.bigscreen.service.IDayAmService;
import com.sf.bigscreen.utils.DateToIntegerUtil;
import com.sf.bigscreen.utils.GetEnergyPlatformTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author: bi xuan
 * @Date: 2021/6/24 15:58
 * @Description:
 **/
@Slf4j
@Service
public class DayAmServiceImpl extends ServiceImpl<IDayAmMapper, DayAm> implements IDayAmService {
    @Resource
    private IDayAmMapper iDayAmMapper;

    @Resource
    private ITableConfigMapper iTableConfigMapper;

    @Autowired
    private GetEnergyPlatformTokenUtil getEnergyPlatformTokenUtil;

    @Value("${third.url}")
    private String thirdUrl;

    /**
     * =================================================================================================================================
     * 同步时间段内的多条数据
     */

    /**
     * 同步时间段内的全校电量信息
     *
     * @return
     */
    @Override
    public void addOrUpdateDayAmAllInfoRangeTime(String dateStart, String dateEnd) {
        String accessToken = getToken();
        String today = DateUtil.today();
        DateTime startDate = DateUtil.parse(dateStart, "yyyy-MM-dd");
        DateTime endDate = DateUtil.parse(dateEnd, "yyyy-MM-dd");
        Integer integer = iDayAmMapper.deleteDayAmAllInfo(startDate, endDate);
        log.info("删除全校数据：" + dateStart + "--" + dateEnd + "结果：" + integer + "条记录");
        StringBuilder builder = new StringBuilder(thirdUrl);
        TableConfig tableConfig = iTableConfigMapper.selectOne(new LambdaQueryWrapper<TableConfig>().eq(TableConfig::getTableName, "dayam").eq(TableConfig::getInfoStyle, "All"));
        String url = builder.append("/plat/api/dayAm/getDayAmAllInfoByTimeRange").append("?dateStart=").append(dateStart).append("&dateEnd=").append(dateEnd).toString();
        String body = HttpRequest.get(url).header("Authorization", accessToken).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Object data = jsonObject.get("data");
        JSONArray dataJsonArray = JSONUtil.parseArray(data);
        for (Object o : dataJsonArray) {
            JSONObject jsonObject1 = JSONUtil.parseObj(o);
            Integer selectYear = Integer.valueOf(jsonObject1.get("selectYear").toString());
            Integer selectMonth = Integer.valueOf(jsonObject1.get("selectMonth").toString());
            Integer selectDay = Integer.valueOf(jsonObject1.get("selectDay").toString());
            Double zgross = Double.valueOf(jsonObject1.get("zgross").toString());
            Double workData = Double.valueOf(jsonObject1.get("workData").toString());
            Double unWorkData = Double.valueOf(jsonObject1.get("unWorkData").toString());
            Integer workingDayType = Integer.valueOf(jsonObject1.get("workingDayType").toString());

            String i = String.valueOf(selectYear * 10000 + selectMonth * 100 + selectDay);
            String date = new StringBuffer(i).insert(4, "-").insert(7, "-").toString();
            Date parse = DateUtil.parse(date, "yyyy-MM-dd");
            DayAm dayAm = new DayAm();
            dayAm.setInfoStyle("All");
            dayAm.setInfoIndex("");
            dayAm.setInfoName("全校");
            dayAm.setTheDay(parse);
            dayAm.setZGross(zgross);
            dayAm.setWorkGross(workData);
            dayAm.setUnWorkGross(unWorkData);
            dayAm.setWorkDay(workingDayType);

            int insert = iDayAmMapper.insert(dayAm);
            log.info("dayam插入全校记录" + date + "结果：(0：失败 1：成功)" + insert);
        }
    }

    /**
     * 同步时间段的区域电量信息
     *
     * @return
     */
    @Override
    public void addOrUpdateDayAmAreaInfoRangeTime(Integer id, String dateStart, String dateEnd) {
        String accessToken = getToken();
        String today = DateUtil.today();
        StringBuilder builder = new StringBuilder(thirdUrl);
        TableConfig tableConfig = iTableConfigMapper.selectOne(new LambdaQueryWrapper<TableConfig>().eq(TableConfig::getTableName, "dayam").eq(TableConfig::getInfoStyle, "Area"));
        String url = builder.append("/plat/api/dayAm/getDayAmAreaInfoByTimeRange").append("?dateStart=").append(dateStart)
                .append("&dateEnd=").append(dateEnd).append("&id=").append(id).toString();
        String body = HttpRequest.get(url).header("Authorization", accessToken).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Object data = jsonObject.get("data");
        JSONArray dataJsonArray = JSONUtil.parseArray(data);
        DateTime startDate = DateUtil.parse(dateStart, "yyyy-MM-dd");
        DateTime endDate = DateUtil.parse(dateEnd, "yyyy-MM-dd");
        Integer integer = iDayAmMapper.deleteDayAmAreaInfo(id, startDate, endDate);
        log.info("删除区域数据：" + dateStart + "--" + dateEnd + "结果：" + integer + "条记录");
        for (Object o : dataJsonArray) {
            JSONObject jsonObject1 = JSONUtil.parseObj(o);
            Integer selectYear = Integer.valueOf(jsonObject1.get("selectYear").toString());
            Integer selectMonth = Integer.valueOf(jsonObject1.get("selectMonth").toString());
            Integer selectDay = Integer.valueOf(jsonObject1.get("selectDay").toString());
            Double zgross = Double.valueOf(jsonObject1.get("zgross").toString());
            Double workData = Double.valueOf(jsonObject1.get("workData").toString());
            Double unWorkData = Double.valueOf(jsonObject1.get("unWorkData").toString());
            Integer workingDayType = Integer.valueOf(jsonObject1.get("workingDayType").toString());
            String areaName = jsonObject1.get("areaName").toString();
            String areaId = jsonObject1.get("areaId").toString();

             String i = String.valueOf(selectYear * 10000 + selectMonth * 100 + selectDay);
            String date = new StringBuffer(i).insert(4, "-").insert(7, "-").toString();
            Date parse = DateUtil.parse(date, "yyyy-MM-dd");
            DayAm dayAm = new DayAm();
            dayAm.setInfoStyle("Area");
            dayAm.setInfoIndex(areaId);
            dayAm.setInfoName(areaName);
            dayAm.setTheDay(parse);
            dayAm.setZGross(zgross);
            dayAm.setWorkGross(workData);
            dayAm.setUnWorkGross(unWorkData);
            dayAm.setWorkDay(workingDayType);

            int insert = iDayAmMapper.insert(dayAm);
            log.info("dayam插入区域记录" + date + "结果：(0：失败 1：成功)" + insert);
        }
    }

    /**
     * 获取时间段的部门下的用电信息
     *
     * @return
     */
    @Override
    public void addOrUpdateDayAmDepartmentInfoRangeTime(Integer id, String dateStart, String dateEnd) {
        String accessToken = getToken();
        String today = DateUtil.today();
        StringBuilder builder = new StringBuilder(thirdUrl);
        TableConfig tableConfig = iTableConfigMapper.selectOne(new LambdaQueryWrapper<TableConfig>().eq(TableConfig::getTableName, "dayam").eq(TableConfig::getInfoStyle, "Part"));
        String url = builder.append("/plat/api/dayAm/getDayAmDepartmentInfoByTimeRange").append("?dateStart=").append(dateStart)
                .append("&dateEnd=").append(dateEnd).append("&id=").append(id).toString();
        String body = HttpRequest.get(url).header("Authorization", accessToken).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Object data = jsonObject.get("data");
        JSONArray dataJsonArray = JSONUtil.parseArray(data);
        DateTime startDate = DateUtil.parse(dateStart, "yyyy-MM-dd");
        DateTime endDate = DateUtil.parse(dateEnd, "yyyy-MM-dd");
        Integer integer = iDayAmMapper.deleteDayAmDepartmentInfo(id, startDate, endDate);
        log.info("删除部门数据：" + dateStart + "--" + dateEnd + "结果：" + integer + "条记录");
        for (Object o : dataJsonArray) {
            JSONObject jsonObject1 = JSONUtil.parseObj(o);
            Integer selectYear = Integer.valueOf(jsonObject1.get("selectYear").toString());
            Integer selectMonth = Integer.valueOf(jsonObject1.get("selectMonth").toString());
            Integer selectDay = Integer.valueOf(jsonObject1.get("selectDay").toString());
            Double zgross = Double.valueOf(jsonObject1.get("zgross").toString());
            Double workData = Double.valueOf(jsonObject1.get("workData").toString());
            Double unWorkData = Double.valueOf(jsonObject1.get("unWorkData").toString());
            Integer workingDayType = Integer.valueOf(jsonObject1.get("workingDayType").toString());
            String departmentName = jsonObject1.get("departmentName").toString();
            String department = jsonObject1.get("department").toString();

            String i = String.valueOf(selectYear * 10000 + selectMonth * 100 + selectDay);
            String date = new StringBuffer(i).insert(4, "-").insert(7, "-").toString();
            Date parse = DateUtil.parse(date, "yyyy-MM-dd");
            DayAm dayAm = new DayAm();
            dayAm.setInfoStyle("Part");
            dayAm.setInfoIndex(department);
            dayAm.setInfoName(departmentName);
            dayAm.setTheDay(parse);
            dayAm.setZGross(zgross);
            dayAm.setWorkGross(workData);
            dayAm.setUnWorkGross(unWorkData);
            dayAm.setWorkDay(workingDayType);

            int insert = iDayAmMapper.insert(dayAm);
            log.info("dayam插入部门记录" + date + "结果：(0：失败 1：成功)" + insert);
        }
    }

    /**
     * 同步时间段的建筑下的电量信息
     *
     * @return
     */
    @Override
    public void addOrUpdateDayAmArcInfoRangeTime(Integer id, String dateStart, String dateEnd) {
        String accessToken = getToken();
        String today = DateUtil.today();
        StringBuilder builder = new StringBuilder(thirdUrl);
        TableConfig tableConfig = iTableConfigMapper.selectOne(new LambdaQueryWrapper<TableConfig>().eq(TableConfig::getTableName, "dayam").eq(TableConfig::getInfoStyle, "Arc"));
        String url = builder.append("/plat/api/dayAm/getDayAmArcInfoByTimeRange").append("?dateStart=").append(dateStart)
                .append("&dateEnd=").append(dateEnd).append("&id=").append(id).toString();
        String body = HttpRequest.get(url).header("Authorization", accessToken).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Object data = jsonObject.get("data");
        JSONArray dataJsonArray = JSONUtil.parseArray(data);
        for (Object o : dataJsonArray) {
            JSONObject jsonObject1 = JSONUtil.parseObj(o);
            Integer selectYear = Integer.valueOf(jsonObject1.get("selectYear").toString());
            Integer selectMonth = Integer.valueOf(jsonObject1.get("selectMonth").toString());
            Integer selectDay = Integer.valueOf(jsonObject1.get("selectDay").toString());
            Double zgross = Double.valueOf(jsonObject1.get("zgross").toString());
            Double workData = Double.valueOf(jsonObject1.get("workData").toString());
            Double unWorkData = Double.valueOf(jsonObject1.get("unWorkData").toString());
            Integer workingDayType = Integer.valueOf(jsonObject1.get("workingDayType").toString());
            String architectureName = jsonObject1.get("architectureName").toString();
            String architectureId = jsonObject1.get("architectureId").toString();

            String i = String.valueOf(selectYear * 10000 + selectMonth * 100 + selectDay);
            String date = new StringBuffer(i).insert(4, "-").insert(7, "-").toString();
            Date parse = DateUtil.parse(date, "yyyy-MM-dd");
            DayAm dayAm = new DayAm();
            dayAm.setInfoStyle("Arc");
            dayAm.setInfoIndex(architectureId);
            dayAm.setInfoName(architectureName);
            dayAm.setTheDay(parse);
            dayAm.setZGross(zgross);
            dayAm.setWorkGross(workData);
            dayAm.setUnWorkGross(unWorkData);
            dayAm.setWorkDay(workingDayType);

            int insert = iDayAmMapper.insert(dayAm);
            log.info("dayam插入区域记录" + date + "结果：(0：失败 1：成功)" + insert);
        }
    }

    /**
     * 同步时间段下的电表的用电信息
     *
     * @return
     */
    @Override
    public void addOrUpdateDayAmInfoRangeTime(Integer id, String dateStart, String dateEnd) {
        String accessToken = getToken();
        String today = DateUtil.today();
        StringBuilder builder = new StringBuilder(thirdUrl);
        TableConfig tableConfig = iTableConfigMapper.selectOne(new LambdaQueryWrapper<TableConfig>().eq(TableConfig::getTableName, "dayam").eq(TableConfig::getInfoStyle, "Meter"));
        String url = builder.append("/plat/api/dayAm/getDayAmInfoByTimeRange").append("?dateStart=").append(dateStart)
                .append("&dateEnd=").append(dateEnd).append("&id=").append(id).toString();
        String body = HttpRequest.get(url).header("Authorization", accessToken).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Object data = jsonObject.get("data");
        JSONArray dataJsonArray = JSONUtil.parseArray(data);
        DateTime startDate = DateUtil.parse(dateStart, "yyyy-MM-dd");
        DateTime endDate = DateUtil.parse(dateEnd, "yyyy-MM-dd");
        Integer integer = iDayAmMapper.deleteDayAmMeterInfo(id, startDate, endDate);
        log.info("删除电表数据：" + dateStart + "--" + dateEnd + "结果：" + integer + "条记录");
        for (Object o : dataJsonArray) {
            JSONObject jsonObject1 = JSONUtil.parseObj(o);
            Integer selectYear = Integer.valueOf(jsonObject1.get("selectYear").toString());
            Integer selectMonth = Integer.valueOf(jsonObject1.get("selectMonth").toString());
            Integer selectDay = Integer.valueOf(jsonObject1.get("selectDay").toString());
            Double zgross = Double.valueOf(jsonObject1.get("zGross").toString());
//            Double workData = Double.valueOf(jsonObject1.get("workData").toString());
//            Double unWorkData = Double.valueOf(jsonObject1.get("unWorkData").toString());
            Integer workingDayType = Integer.valueOf(jsonObject1.get("workingDayType").toString());
            String amMeterName = jsonObject1.get("amMeterName").toString();
            String amMeter_ID = jsonObject1.get("amMeter_ID").toString();

            String i = String.valueOf(selectYear * 10000 + selectMonth * 100 + selectDay);
            String date = new StringBuffer(i).insert(4, "-").insert(7, "-").toString();
            Date parse = DateUtil.parse(date, "yyyy-MM-dd");
            DayAm dayAm = new DayAm();
            dayAm.setInfoStyle("Meter");
            dayAm.setInfoIndex(amMeter_ID);
            dayAm.setInfoName(amMeterName);
            dayAm.setTheDay(parse);
            dayAm.setZGross(zgross);
//            dayAm.setWorkGross(workData);
//            dayAm.setUnWorkGross(unWorkData);
            dayAm.setWorkDay(workingDayType);

            int insert = iDayAmMapper.insert(dayAm);
            log.info("dayam插入单表记录" + date + "结果：(0：失败 1：成功)" + insert);
        }
    }


    /**
     * 获取token
     *
     * @return
     */
    private String getToken() {
        return getEnergyPlatformTokenUtil.getEnergyToken();
    }

}
